package com.i2863.shiroDemo.web;

import com.i2863.shiroDemo.dto.RoleInfo;
import com.i2863.shiroDemo.dto.UserInfo;
import com.i2863.shiroDemo.ex.BusinessException;
import com.i2863.shiroDemo.ex.RoleAuthException;
import com.i2863.shiroDemo.ex.RoleDisableException;
import com.i2863.shiroDemo.config.Constant;
import com.i2863.shiroDemo.dto.TopDirectoryInfo;
import com.i2863.shiroDemo.entity.Permission;
import com.i2863.shiroDemo.service.IPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@Slf4j
public class HomeController extends BaseController {

    @Resource
    private IPermissionService iPermissionService;

    @RequestMapping("/*")
    public void toHtml() {

    }

    @RequestMapping("favicon.ico")
    public String getFavicon() {
        return "redirect:static/favicon.ico";
    }

    @RequestMapping({"/", "undefined", "/index"})
    public String index(Model model) {

        List<TopDirectoryInfo> topDirectoryList = new ArrayList<>();
        //获取当前用户角色信息
        UserInfo userInfo = this.getUserInfo();
        if (userInfo == null) {
            return "redirect:/login";
        }
        RoleInfo roleInfo = userInfo.getRoleInfo();
        List<Permission> permissionList = iPermissionService.getTopDirectoryPermissions();
        Permission permission = this.getSuperPermission();
        boolean isSuper = roleInfo.getPermissionIds().contains("," + permission.getId() + ",");
        if (permissionList != null) {
            if (isSuper) {
                permissionList.forEach(p -> topDirectoryList.add(new TopDirectoryInfo(p.getPermissionName(), p.getPermissionCode())));
            } else {
                permissionList.forEach(p -> {
                    if (roleInfo.getPermissionIds().contains("," + p.getId() + ",")) {
                        topDirectoryList.add(new TopDirectoryInfo(p.getPermissionName(), p.getPermissionCode()));
                    }
                });
            }
        }

        model.addAttribute("topDirectoryList", topDirectoryList);
        model.addAttribute("roleName", roleInfo.getRoleName());

        return "index";
    }

    @RequestMapping("login")
    public String login(HttpServletRequest request) throws BusinessException {
        // 判断是否已登录，如果已登录直接跳转到首页
        UserInfo userInfo = this.getUserInfo();
        if (userInfo != null) {
            return "redirect:/";
        }

        // 登录失败从request中获取shiro处理的异常信息.
        // shiroLoginFailure:就是shiro异常类的全类名.
        String exception = (String) request.getAttribute("shiroLoginFailure");

        Session session = SecurityUtils.getSubject().getSession();
        if (exception != null) {
            if (AccountException.class.getName().equals(exception)) {
                log.warn("AccountException ---> 账号或密码错误！");
                throw new BusinessException(Constant.YES_ERROR, "账号或密码错误！");
            } else if (RoleDisableException.class.getName().equals(exception)) {
                log.warn("RoleDisableException ---> 用户角色已被禁用！");
                throw new BusinessException(Constant.YES_ERROR, "用户角色已被禁用！");
            } else if (RoleAuthException.class.getName().equals(exception)) {
                log.warn("RoleDisableException ---> 用户角色无权限！");
                throw new BusinessException(Constant.YES_ERROR, "用户角色无权限，不能登录！");
            } else if (DisabledAccountException.class.getName().equals(exception)) {
                log.warn("DisabledAccountException ---> 账号已禁用！");
                throw new BusinessException(Constant.YES_ERROR, "账号已禁用！");
            } else if (LockedAccountException.class.getName().equals(exception)) {
                log.warn("LockedAccountException ---> 账号已锁定！");
                throw new BusinessException(Constant.YES_ERROR, "账号已锁定，请联系管理员解锁！");
            } else if ("kaptchaValidateFailed".equals(exception)) {
                log.warn("kaptchaValidateFailed ---> 验证码错误！");
                throw new BusinessException(Constant.YES_ERROR, "验证码错误！");
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                //密码最多错误输入5次
                /*int loginErrorCount = Integer.parseInt(Optional.ofNullable(session.getAttribute(Constant.LOGIN_ERROR_COUNT)).orElse("0") + "");
                if (++loginErrorCount == Constant.MAX_LOGIN_ERROR_NUM) {
                    //锁定账号
                    User user = iUserService.getById(Integer.parseInt(Optional.ofNullable(session.getAttribute(Constant.LOGIN_USER_ID)).orElse("0") + ""));
                    if (user != null) {
                        user.setState(2);
                        iUserService.updateById(user);
                    }
                }
                session.setAttribute(Constant.LOGIN_ERROR_COUNT, loginErrorCount);*/
                log.warn("AccountException ---> 密码错误！");
                //throw new BusinessException(Constant.YES_ERROR, "密码错误，您还有" + (Constant.MAX_LOGIN_ERROR_NUM - loginErrorCount) + "机会！");
                throw new BusinessException(Constant.YES_ERROR, "密码错误！");
            } else {
                log.warn("else ---> " + exception);
                throw new BusinessException(Constant.YES_ERROR, "未知错误！");
            }
        }
        //初始化登录错误次数
        //session.setAttribute(Constant.LOGIN_ERROR_COUNT, 0);
        //记录登录IP地址
        session.setAttribute(Constant.LOGIN_IP_ADDRESS, this.getIpAddress(request));
        // 此方法不处理登录成功,由shiro进行处理
        return "login";
    }

    @RequestMapping("kickout")
    public String kickout() {
        return "kickout";
    }

}